<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { io } from 'socket.io-client'
const socket = io('wss://sock.xxgxiaoyu.xyz:3000')
const PeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
const peerRTC = new PeerConnection()
const videoChat = ref(null)
const remoteVideo = ref(null)
// while(socket.readyState !== 1){
//     console.log('socket.readyState ==> ',socket.readyState)
// }

		
const msgList = ref([])
const isUserInfo = ref({})

const sendID_offer = ref('')
const sendMsgtext = ref('')

let sendID_answer = null

let targetType = null
const setUserInfo = (userInfo) => {
    window.localStorage.setItem('userinfo',JSON.stringify(userInfo))
    isUserInfo.value = userInfo
}

// navigator.mediaDevices.getUserMedia({
//             video: true,
//             audio: true
//         }).then(stream => {
//             // videoChat.value.srcObject = stream;
//             stream.getTracks().forEach(track => {
//                 peerRTC.addTrack(track, stream)
//             })
//         })

// 发送消息
const sendText = () => {
    if(!sendMsgtext.value || !sendID_offer.value) return;
    socket.emit('sendtextmsg',JSON.stringify({sendID:sendID_offer.value,text:sendMsgtext.value}))
}

//接收消息
socket.on('receptiontextmsg',(msg)=>{
    console.log('msg ==> ',msg)
    msgList.value.push(msg)
})
const sendCallhandle = () => {
    sendCall()
}
const closeCallhandle = () => {
    if (peerRTC) {
        // peerRTC.ontrack = null;
        // peerRTC.onremovetrack = null;
        // peerRTC.onremovestream = null;
        // peerRTC.onicecandidate = null;
        // peerRTC.oniceconnectionstatechange = null;
        // peerRTC.onsignalingstatechange = null;
        // peerRTC.onicegatheringstatechange = null;
        // peerRTC.onnegotiationneeded = null;

        if (remoteVideo.value.srcObject) {
        remoteVideo.value.srcObject.getTracks().forEach((track) => track.stop());
        }

        if (videoChat.value.srcObject) {
            videoChat.value.srcObject.getTracks().forEach((track) => track.stop());
        }

        peerRTC.close();
    }

    remoteVideo.value.removeAttribute("src");
    remoteVideo.value.removeAttribute("srcObject");
    videoChat.value.removeAttribute("src");
    videoChat.value.removeAttribute("srcObject");

    // socket.emit('callclose',JSON.stringify({user_id:isUserInfo.value.user_id}))
}

socket.on('callclose',()=>{
    closeCall()
})

peerRTC.ontrack = e => {

	if (e && e.streams) {
		remoteVideo.value.srcObject = e.streams[0];
	}	
};

// peerRTC.onaddstream = e => {

// 	if (e && e.streams) {
// 		remoteVideo.value.srcObject = e.streams[0];
// 	}	
// };

peerRTC.ondatachannel = e => {
    // const channel = e.channel;
    // channel.onmessage = e => {
    //     msgList.value.push('RTC连接上了')
    // }
    
};

const channel = peerRTC.createDataChannel('messagechannel')
setInterval(()=>{
    const connectionState = peerRTC.connectionState
    console.log('connectionState ==> ',connectionState)
},5000)

// 视频通话
const sendCall = async () => {
    console.log('sendCall函数执行开始')

    targetType = 'offer'
    let stream;
	try {
		stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
		videoChat.value.srcObject = stream
	} catch {
		return;
	}

	stream.getTracks().forEach(track => {
		peerRTC.addTrack(track, stream);
	});
    const offer = await createoffer()
    console.log('offer ===> ',offer)
    socket.emit('sendcall',JSON.stringify({offer,sendtoID:sendID_offer.value,user_id:isUserInfo.value.user_id}))
    console.log('sendCall函数执行结束')
}

const createoffer = async () => {
    const offer = await peerRTC.createOffer({iceRestart:true});
	await peerRTC.setLocalDescription(offer);
    console.log('createoffer函数执行结束')
    return offer
}

socket.on('sendcallmsg',async (data)=>{
    console.log('sendcallmsg接收到消息')

//    const { offer:{type:offertype, sdp:offersdp}, answer:{type:answertype, sdp:answersdp} , user_id } = JSON.parse(data)
    const res = JSON.parse(data)
    if(res.offer){
        targetType = 'answer'
        const answerCall = confirm("你要接听吗?");
        if(answerCall){
            await throughcall(new RTCSessionDescription({type:res.offer.type, sdp:res.offer.sdp}),res.user_id)
        }
    }else{
        peerRTC.setRemoteDescription(new RTCSessionDescription({ type:res.answer.type, sdp:res.answer.sdp }));
    }
})

peerRTC.onicecandidate = e => {
	// if (e.candidate) {
	// 	peerRTC.addIceCandidate(e.candidate);
	// } 
        if (e.candidate) {
            console.log(targetType)
            console.log('candidate ===> ',e.candidate)
            if(targetType === 'answer'){
                socket.emit('answer_ice',JSON.stringify({
                    user_id:sendID_answer,
                    iceCandidate:e.candidate
                }))
            }else if(targetType === 'offer'){
                socket.emit('offer_ice',JSON.stringify({
                    user_id:sendID_offer.value,
                    iceCandidate:e.candidate
                }))
            }
            // console.log('addIceCandidate ==> ', e.candidate)
        }else{
            // sendCall()
            console.log('remoteDescription is ==> ', peerRTC.remoteDescription)
        }
};

socket.on('offer_ice_msg',async (data)=>{
    console.log('offer_ice_msg接收到消息')
    const { iceCandidate } = JSON.parse(data)
    // console.log(JSON.parse(data))
    await checkRemoteDescription()
    console.log('remoteDescription is offer_ice_msg==> ', peerRTC.remoteDescription)
    peerRTC.addIceCandidate(iceCandidate).catch(err=>{
        // peerRTC.restartIce()
        // createoffer()
        // socket.emit('sendcall',JSON.stringify({offer,sendtoID:sendID_offer.value,user_id:isUserInfo.value.user_id}))
        console.log('offer_ice_msg addIceCandidate err ==> ',err)
    }).then(()=>{
        console.log('offer_ice_msg addIceCandidate success')
    })
    // peerRTC.addIceCandidate(new RTCIceCandidate(iceCandidate))
})

const checkRemoteDescription = async () => {
    return new Promise((resolve,reject)=>{
        const timer = setInterval(()=>{
            if(peerRTC.remoteDescription){
                console.log('211:remoteDescription is checkRemoteDescription==> ', peerRTC.remoteDescription)
                resolve()
                clearInterval(timer)
            }
        },500)
        setTimeout(()=>{
            if(peerRTC.remoteDescription){
                resolve()
            }else{
                reject()
            }
        },10000)
    })
}

socket.on('answer_ice_msg',async (data)=>{
    console.log('answer_ice_msg接收到消息')
    const { iceCandidate } = JSON.parse(data)
    await checkRemoteDescription()
    console.log('remoteDescription is answer_ice_msg==> ', peerRTC.remoteDescription)
    await peerRTC.addIceCandidate(iceCandidate).catch(err=>{
        // console.log(iceCandidate)
        console.log('answer_ice_msg addIceCandidate err ==> ',err)
    }).then(()=>{
        console.log('answer_ice_msg addIceCandidate success')
    })
    // peerRTC.addIceCandidate(new RTCIceCandidate(iceCandidate))
})

const throughcall = async (offerSdp,sendtoID) => {
    console.log('throughcall函数执行')
    sendID_answer = sendtoID
    let stream;
	try {
		stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
		videoChat.value.srcObject = stream;
	} catch {
		return;
	}

	stream.getTracks().forEach(track => {
		peerRTC.addTrack(track, stream);
	});

	await peerRTC.setRemoteDescription(offerSdp);
    // console.log(peerRTC.remoteDescription)
    peerRTC.restartIce()
    const answer = await peerRTC.createAnswer();
	await peerRTC.setLocalDescription(answer);
    socket.emit('sendcall',JSON.stringify({answer,sendtoID}))
}


// 连接
socket.on('connect',()=>{
    console.log('socket连接成功')
    socket.on('createroom',({room,user_id})=>{
        setUserInfo({user_id,room})
    })
})

// setTimeout(e=>{
//     console.log(peerRTC.remoteDescription)
//     peerRTC.restartIce()
// },20000)

onMounted(() => {

    videoChat.value.onloadeddata = () => {
		videoChat.value.play();
	}

    remoteVideo.value.onloadeddata = () => {
        console.log(' ==> remoteVideo.onloadeddata <== ')
        remoteVideo.value.play();
    }
    // peerRTC.ontrack = (e) => {
    //         console.log('ontrack ==> ',e)
    //         if (e && e.streams) {
    //             remoteVideo.value.srcObject = e.streams[0]
    //         }
    // }

    socket.on('connect',()=>{

    
    // socket.onmessage = (e) =>{
    //     const { type, sdp, iceCandidate } = JSON.parse(e.data)
    //     console.log('iceCandidate ==> ',iceCandidate)
    //     if(type === 'offer_ice'){
    //         peerRTC.addIceCandidate(sdp)
    //     }else if(type === 'offer'){
    //         navigator.mediaDevices.getUserMedia()
    //         const offerSdp = new RTCSessionDescription(sdp)
    //         peerRTC.setRemoteDescription(offerSdp).then(() => {
    //             peerRTC.createAnswer().then(answer => {
    //                 peerRTC.setLocalDescription(answer)
    //                 socket.send(JSON.stringify(answer))
    //             })
    //         })
    //     }
    // }
        

        // socket.on('msg',(data)=>{
        //     const { type, sdp, iceCandidate } = JSON.parse(data)
        //     if(type === 'offer_ice' || type === 'answer_ice'){
        //         peerRTC.addIceCandidate(iceCandidate)
        //     }
        // })

        // socket.on('msg',(data)=>{
        //     const { type, sdp, iceCandidate } = JSON.parse(data);
        //     console.log(type)
        //     if (type === 'offer') {
        //     navigator.mediaDevices.getUserMedia({
        //         video: true,
        //         audio: true
        //     }).then(stream => {
        //         videoChat.value.srcObject = stream;
        //         stream.getTracks().forEach(track => {
        //             peerRTC.addTrack(track, stream)
        //         })
        //     })
        //         const offerSdp = new RTCSessionDescription({ type, sdp });
        //         peerRTC.setRemoteDescription(offerSdp).then(() => {
        //             peerRTC.createAnswer(answer => {
        //                 socket.emit('msg',JSON.stringify(answer))
        //                 peerRTC.setLocalDescription(answer)
        //             });
        //         });
        //     }

            // if (type === 'answer') {
			// 	peerRTC.setRemoteDescription(new RTCSessionDescription({ type, sdp }));
			// } else if (type === 'answer_ice') {
			// 	peerRTC.addIceCandidate(iceCandidate);
			// } else if (type === 'offer') {
			// 	startLive(new RTCSessionDescription({ type, sdp }));
			// } else if (type === 'offer_ice') {
			// 	peerRTC.addIceCandidate(iceCandidate);
			// }
        // })

        

    

        // peerRTC.onicecandidate = (e) => {
        //     console.log('e.candidate ==> ',e.candidate)
        //     if(e.candidate){
        //         socket.emit('msg',JSON.stringify({
        //             type: 'offer_ice',
        //             iceCandidate: e.candidate
        //         }))
        //     }
        // }

        

        // peerRTC.createOffer().then(offer => {
        //     console.log(offer)
        //     peerRTC.setLocalDescription(offer)
        //     socket.emit('msg',JSON.stringify(offer))
        // })

       
    })
})
</script>

<template>
    <h1 style="text-align: center;">视频聊天-DEBUG</h1>
    <div class="text-chat">
        <div class="myuserinfo">你的ID:{{ isUserInfo.user_id }}</div>
        <div class="text-chat-content">
            <div class="text-chat-list">
                <div class="text-chat-item" v-for="(item,index) in msgList" :key="index">
                    <div class="text-chat-item-name">{{item.name}}</div>
                    <div class="text-chat-item-text">{{item.text}}</div>
                </div>
            </div>
        </div>
        <div class="text-chat-input">
            <input type="text" placeholder="请输入发送ID" v-model="sendID_offer">
            <input type="text" placeholder="请输入聊天内容" v-model="sendMsgtext">
            <button @click="sendText">发送</button>
            <button @click="sendCallhandle">电话</button>
            <button @click="closeCallhandle">结束通话</button>
        </div>
    </div>
    <div class="video-chat">
        <video autoplay ref="videoChat" muted></video>
        <video autoplay ref="remoteVideo"></video>
    </div>

</template>

<style lang="less" scoped>
.video-chat{
    width: 1000px;
    height: 400px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 0 auto;
    inset: 5px;
    margin-top: 5%;
    video{
        display: flex;
        width: 50%;
        max-height: 580px;
        margin: 0 15px;
    }
}

.text-chat{
    width: 450px;
    height: 450px;
    margin: 0 auto;
    .text-chat-content{
        width: 100%;
        height: 80%;
        border: 1px solid #1189ac;
        .text-chat-list{
            width: 100%;
        }
    }   
}
</style>